require 'digest'

class User < ActiveRecord::Base
  
  acts_as_authentic
  
  validates_presence_of :last_name
  validates_presence_of :first_name
  validates_presence_of :email
  validates_presence_of :password, :if => :should_validate_password?
  validates_length_of :password, :in => 4..10, :if => :should_validate_password?
  validates_confirmation_of :password, :if => :should_validate_password?
  validates_presence_of :birthday
  validates_presence_of :locality
  validates_presence_of :land_id
  
  validates_presence_of :security_level
  
  attr_accessor :updating_password
  
  belongs_to :land
  has_many :user_tournaments, :dependent => :destroy
  has_many :tournaments, :through => :user_tournaments
  
  def should_validate_password?
    new_record?
  end
  
  # enregistrement de la valeur salt et hash du mot de passe => appele avant la methode "save" (@user.save() dans le controller)
  def before_save
    if(self.salt == nil)
      self.salt = random_numbers(5)
      self.password = Digest::MD5.hexdigest(self.salt+self.password)
    end
  end
  
  private
  
  # random sequence
  def random_numbers(len)
    numbers = ("0".."9").to_a
    newrand = ""
    1.upto(len) { |i| newrand << numbers[rand(numbers.size - 1)] }
    return newrand
  end
end
